package com.example.patients;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {

    private EditText etName, etPwd;
    private Button btnLogin;
    private SharedPreferences sp;
    private CheckBox cb;
    private Boolean aBoolean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        etName = findViewById(R.id.et_name);
        etPwd = findViewById(R.id.et_pwd);
        btnLogin = findViewById(R.id.btn_login);
        cb = findViewById(R.id.cb);
        sp = getSharedPreferences("zidong", Context.MODE_PRIVATE);
        aBoolean = sp.getBoolean("cb_checked", false);
        if (aBoolean) {
            Intent intent = new Intent(LoginActivity.this, BeginActivity.class);
            startActivity(intent);
            finish();
        }

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = etName.getText().toString().trim();
                String pwd = etPwd.getText().toString().trim();
                if (name.equals("admin") && pwd.equals("admin")) {
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(LoginActivity.this, BeginActivity.class);
                    intent.putExtra("name", name);
                    intent.putExtra("pwd", pwd);  //展示账号密码功能
                    startActivity(intent);
                    finish();

                }else if (TextUtils.isEmpty(name)){
                    Toast.makeText(LoginActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show();
                }else if (TextUtils.isEmpty(pwd)){
                    Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(LoginActivity.this, "登录失败！用户名或密码不正确", Toast.LENGTH_LONG).show();
                }
                SharedPreferences.Editor editor = sp.edit();
                if (cb.isChecked()) {
                    editor.putString("cb_name", name);
                    editor.putString("cb_pwd", pwd);
                    editor.putBoolean("cb_checked", true);
                } else {
                    editor.putBoolean("cb_checked", false);
                }
                editor.apply();
            }

        });

    }
}
